﻿/** 
 * Copyright 2010 NUMKIT.COM (contact: opensource@numkit.com)
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 * 
 * @author 陈超
 * @version 1.0
 */
import flash.external.ExternalInterface;
import mx.utils.Delegate;
class Piece {
	public static var LABEL_FORMAT_VALUE = 0;
	public static var LABEL_FORMAT_PERCENT = 1;
	public static var LABEL_FORMAT_BOTH = 2;
	private var id:String;
	private var name:String;
	private var color:Number;
	private var value:Number;
	private var percent:Number;
	private var label:String;
	public function Piece(id:String, name:String, color:Number, value:Number) {
		this.id = id;
		this.name = name;
		this.color = color;
		this.value = value;
	}
	public function initPercent(total:Number):Void {
		percent = value*100/total;
	}
	//绝对值大于1的保留两位小数,小于等于1的保留3位小数
	public static function formatNumber(n:Number):Number {
		if (Math.abs(n)<=1) {
			return Math.round(n*1000)/1000;
		} else {
			return Math.round(n*100)/100;
		}
	}
	public function getLabel(labelFormat:Number):String {
		if (labelFormat == LABEL_FORMAT_VALUE) {
			return name+" = "+String(formatNumber(value));
		} else if (labelFormat == LABEL_FORMAT_PERCENT) {
			return name+" = "+String(formatNumber(percent))+" %";
		} else if (labelFormat == LABEL_FORMAT_BOTH) {
			return name+" = "+String(formatNumber(value))+" ("+String(formatNumber(percent))+" %)";
		} else {
			return "";
		}
	}
	public function getValue():Number {
		return value;
	}
	public function getColor():Number {
		return color;
	}
	public function registerClickEvent(mc:MovieClip):Void {
		mc.onRelease = Delegate.create(this, onRelease);
	}
	public function onRelease():Void {
		ExternalInterface.call(Constants.PieceClickCallBack, Constants.FlashObjID, id, name, value, percent);
	}
}
